package artid.com.arttogoa;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.easemob.EaseChatFragment;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.SendHxMessage_Utils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI.EaseUserProfileProvider;
import com.hyphenate.easeui.domain.EaseUser;

/**
 * 聊天页面，需要fragment的使用
 *
 */
public class ChatActivity extends BaseActivity implements OnClickListener{
	public static ChatActivity activityInstance;
	String toChatUsername;
	public static EMMessage message=SendHxMessage_Utils.mEMMessage;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_chat);
		initView();
	}

	private void initView() {
		setBack();
		EaseChatFragment chatFragment = new EaseChatFragment();
		// 传入参数
		Bundle args = new Bundle();
		args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
		args.putString(EaseConstant.EXTRA_USER_ID, message.getUserName());
		chatFragment.setArguments(args);
		getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("询价详情页");
		setBack();
		//设置头像
		ArtWorkApp.getInstance().easeUI.setUserProfileProvider(new EaseUserProfileProvider() {

			@Override
			public EaseUser getUser(String username) {
				// TODO Auto-generated method stub
				return getUserInfo(username);
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		activityInstance = null;
		SendHxMessage_Utils.mEMMessage=null;
		MainActivity.friendAvatar= null;
		if(AlertUtils.alertDialog!=null){
			AlertUtils.alertDialog.dismiss();
			AlertUtils.alertDialog=null;
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// 点击notification bar进入聊天页面，保证只有一个聊天页面
		String username =  message.getUserName();
		if (toChatUsername.equals(username))
			super.onNewIntent(intent);
		else {
			finish();
			startActivity(intent);
		}

	}

	@Override
	public void onBackPressed() {
		finish();
	}

	public String getToChatUsername() { 
		return toChatUsername;
	}

	private EaseUser getUserInfo(String username){
		EaseUser user = null;
		if(username.equals(EMClient.getInstance().getCurrentUser()))
		{
			//设置自己头像
			user=new EaseUser(username);
			user.setAvatar(AppUtil.getUser().getAvatarurl());
			return user;
		}else{
			//设置好友头像
			user=new EaseUser(username);
			user.setAvatar(MainActivity.friendAvatar);
			return user;
		}

	}
}
